import React, { useState, useRef } from 'react';
import { Modal, Button, Form, message, Select, Popover } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { bindApi, queryApiRelations, selectListNotInSp, unbindApi } from '@/services/channel/sp_api';
import { getApiList } from '@/services/channel/spapi_api';
import { FormattedMessage, useIntl } from '@umijs/max';

interface ApiRelationModalProps {
  visible: boolean;
  onCancel: () => void;
  spId: string | undefined;
}
interface ApiOption {
  key: string;
  value: string;
}

const ApiRelationModal: React.FC<ApiRelationModalProps> = ({ visible, onCancel, spId }) => {
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [apiOptions, setApiOptions] = useState<ApiOption[]>([]);
  const [selectedApi, setSelectedApi] = useState<string>();
  const [form] = Form.useForm();

  const columns: ProColumns<ApiService>[] = [
    {
      title: <FormattedMessage id="pages.spApi.apiCode" defaultMessage="API Code" />,
      dataIndex: 'asCode',
    },
    {
      title: <FormattedMessage id="pages.spApi.apiName" defaultMessage="API Name" />,
      dataIndex: 'asName',
    },
    {
      title: <FormattedMessage id="pages.operating" defaultMessage="操作" />,
      valueType: 'option',
      width: 120,
      render: (_, record) => [
        <a key="unbind" onClick={() => handleUnbind(record.asId)}>
          <FormattedMessage id="pages.spApi.unbind" defaultMessage="解绑" />
        </a>,
      ],
    },
  ];

  const fetchData = async (params: any) => {
    setLoading(true);
    try {
      const result = await queryApiRelations({
        spId,
        current: params.current,
        pageSize: params.pageSize,
      });
      return result;
    } finally {
      setLoading(false);
    }
  };

  const fetchApiOptions = async (spId: string) => {
    try {
      const result = await selectListNotInSp(spId);
      setApiOptions(result.data || []);
    } catch (error) {
      message.error(intl.formatMessage({ id: 'request.error.apiList' }));
    }
  };

  const handlePopoverVisibleChange = (visible: boolean) => {
    setPopoverVisible(visible);
    if (visible) {
      fetchApiOptions(spId);
    }
  };

  const handleUnbind = async (asId: string) => {
    if (!spId) return;

    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.spApi.unbindConfirm.title' }),
      content: intl.formatMessage({ id: 'pages.spApi.unbindConfirm.content' }),
      onOk: async () => {
        await unbindApi({ spId, asId });
        actionRef.current?.reload();
      },
    });
  };

  const handleBindSubmit = async () => {
    if (!selectedApi || !spId) return;

    try {
      await bindApi({ spId, asId: selectedApi });
      message.success(intl.formatMessage({ id: 'request.success.bind' }));
      setPopoverVisible(false);
      actionRef.current?.reload();
      form.resetFields();
      setSelectedApi(undefined);
    } catch (error) {
      message.error(intl.formatMessage({ id: 'request.error.bind' }));
    }
  };

  const popoverContent = (
    <Form form={form} layout="inline">
      <Form.Item 
        label={intl.formatMessage({ id: 'pages.spApi.selectApi' })}
        name="apiId" 
        rules={[{
          required: true,
          message: intl.formatMessage({ id: 'pages.spApi.selectApi.required' })
        }]}
      >
        <Select
          placeholder={intl.formatMessage({ id: 'pages.spApi.selectApi.placeholder' })}
          style={{ width: 200 }}
          onChange={(value: string) => setSelectedApi(value)}
          showSearch
          optionFilterProp="children"
        >
          {apiOptions.map(api => (
            <Select.Option key={api.key} value={api.key}>
              {api.value}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item>
        <Button type="primary" onClick={handleBindSubmit}>
          <FormattedMessage id="pages.spApi.bindButton" defaultMessage="添加绑定" />
        </Button>
      </Form.Item>
    </Form>
  );

  return (
    <Modal
      title={intl.formatMessage({ id: 'pages.spApi.modalTitle' })}
      visible={visible}
      onCancel={onCancel}
      width={800}
      footer={null}
      destroyOnClose
    >
      <ProTable<ApiService>
        actionRef={actionRef}
        rowKey="asId"
        columns={columns}
        request={fetchData}
        loading={loading}
        search={false}
        pagination={false}
        toolBarRender={() => [
          <Popover
            key="add-popover"
            content={popoverContent}
            title={intl.formatMessage({ id: 'pages.spApi.bindTitle' })}
            trigger="click"
            placement="bottom"
            visible={popoverVisible}
            onVisibleChange={handlePopoverVisibleChange}
          >
            <Button type="primary" icon={<PlusOutlined />}>
              <FormattedMessage id="pages.spApi.addBindButton" defaultMessage="添加API绑定" />
            </Button>
          </Popover>,
        ]}
      />
    </Modal>
  );
};

export default ApiRelationModal;